package cn.ffcs.uec.recordsApproval.component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Window;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.recordsApproval.component.bean.RecordsHistoricListboxExtBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.recordsApproval.vo.HistoricTaskVo;
import cn.ffcs.uec.recordsApproval.vo.TaskVo;
import cn.ffcs.uec.staffRecords.manager.AtiSpecificFormManager;
import cn.ffcs.uec.staffRecords.utils.HttpClientUtils;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.NumericUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import cn.ffcs.uom.common.vo.PageInfo;

@Controller
@Scope("prototype")
public class RecordsHistoricListboxExt extends Div implements IdSpace {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6179432015374751503L;

	private RecordsHistoricListboxExtBean bean = new RecordsHistoricListboxExtBean();
	/**
	 * 根据页面参数获取的历史流程任务
	 */
	private List<HistoricTaskVo> hisTaskVosByParams;

	/**
	 * 选中的历史流程记录
	 */
	private HistoricTaskVo historicTaskVo;

	public static final String RECORDS_HISTORIC_LISTBOX_EXT_ZUL = "/pages_nmg/recordsApproval/comp/recordsHistoric_listbox_ext.zul";

	private AtiSpecificFormManager atiSpecificFormManager = (AtiSpecificFormManager) ApplicationContextUtil
			.getBean("atiSpecificFormManager");

	/**
	 * 构造函数
	 */
	public RecordsHistoricListboxExt() {
		Executions.createComponents(RECORDS_HISTORIC_LISTBOX_EXT_ZUL, this,
				null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		// this.onQuery();
	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.bindCombobox();

	}

	public void onReset() {
		PubUtil.clearComponent(this);
		this.bean.getRecordsHistoricListboxPaging().setActivePage(0);

	}

	/**
	 * 选中一条历史记录
	 */
	public void onSelectRequest() {
		Listitem item = this.bean.getRecordsHistoricListbox().getSelectedItem();
		if (null != item) {
			historicTaskVo = (HistoricTaskVo) item.getValue();
			Events.postEvent(ApprovalConstants.ON_SELECTED_TASK, this,
					historicTaskVo);
		}

	}

	/**
	 * 查询历史流程节点
	 */
	public void onQuery() {
		this.bean.getRecordsHistoricListboxPaging().setActivePage(0);
		hisTaskVosByParams = null;

		this.historicTaskQuery();

	}

	/**
	 * 查看选择的历史流程记录
	 */
	public void onView() {
		if (null == historicTaskVo) {
			ZkUtil.showError("没有选中的记录", "错误提示");
			return;
		}
		AtiOaBaseObject oaBaseObject = atiSpecificFormManager
				.getAtiOaBaseObjectByProcInstId(historicTaskVo
						.getProcessInstanceId());
		// String procDefKey = oaBaseObject.getProcDefKey(); //无效
		String procDefKey = oaBaseObject.getProcDefId().toString().split(":")[0];
		Map<String, Object> map = new HashMap<String, Object>();
		// map.put("taskDefKey", task.getTaskDefKey());
		map.put("procDefName", historicTaskVo.getProcDefName());
		map.put("procDefKey", procDefKey);
		map.put("oaBaseObject", oaBaseObject);
		map.put("opType", "onView");
		Window window = null;
		if (ApprovalUtil.OUT_STAFF_ENTRY.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_ENTRY_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_TRIAL.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_TRIAL_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_ADJUST_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_ADJUST_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_RETIRE.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_LEAVE_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_ADJUST_POST.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_ADJUST_POST_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_ENC_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_ENC_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_EDU_ADD.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_EDU_ADD_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_EDU_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_EDU_EDIT_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_PUNISH_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_PUNISH_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_TALENT_TEAM_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_TALENT_TEAM_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_TITLE_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_TITLE_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_TITLE_ADD.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_TITLE_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_PARTYLOG_ADD.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_PARTYLOG_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_PARTYLOG_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_PARTYLOG_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_WORKDATE_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_WORKDATE_VIEW, this, map);
		}
		if (ApprovalUtil.OUT_STAFF_ASS_EDIT.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.OUT_STAFF_ASS_VIEW, this, map);
		}
		if (ApprovalUtil.STAFF_ADJUST_POST.equals(procDefKey)) {
			window = (Window) Executions.createComponents(
					ApprovalConstants.STAFF_ADJUST_POST_VIEW, this, map);
		}
		try {
			window.doModal();
		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void historicTaskQuery() {
		// 1.根据页面参数获取list
		// 流程分类
		Listitem selectedItemListitem = this.bean.getCategoryId()
				.getSelectedItem();
		String categoryId = "";
		if (null != selectedItemListitem) {
			categoryId = (String) this.bean.getCategoryId().getSelectedItem()
					.getValue();
		}
		// 状态
		Listitem statusItem = bean.getIsEnd().getSelectedItem();
		// 开始日期
		Date beginDate = this.bean.getStartTime().getValue();
		// 结束日期
		Date endDate = this.bean.getEndTime().getValue();
		// List<HistoricTaskVo> historicTasks =
		// getHistoricTasks(historicTaskVos,
		// categoryId, beginDate, endDate);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String startTime = "";
		if (!StrUtil.isNullOrEmpty(beginDate)) {
			startTime = sdf.format(beginDate);
		}
		String endTime = "";
		if (!StrUtil.isNullOrEmpty(endDate)) {
			endTime = sdf.format(endDate);
		}
		List<HistoricTaskVo> historicTasks = ApprovalUtil.historicApproval(
				categoryId, startTime, endTime);
		List<HistoricTaskVo> historics = new ArrayList<HistoricTaskVo>();
		if (null == statusItem || StrUtil.isNullOrEmpty(statusItem.getValue())) {
			historics = historicTasks;
		} else if ("0".equals(statusItem.getValue().toString())) {
			if (!StrUtil.isNullOrEmpty(historicTasks)
					&& historicTasks.size() > 0) {
				for (HistoricTaskVo historicTaskVo : historicTasks) {
					if (!StrUtil.isNullOrEmpty(historicTaskVo
							.getCurrentCandidate())) {
						historics.add(historicTaskVo);
					}
				}
			}
		}
		// 结束
		else if ("1".equals(statusItem.getValue().toString())) {
			if (!StrUtil.isNullOrEmpty(historicTasks)
					&& historicTasks.size() > 0) {
				for (HistoricTaskVo historicTaskVo : historicTasks) {
					if (StrUtil.isNullOrEmpty(historicTaskVo
							.getCurrentCandidate())) {
						historics.add(historicTaskVo);
					}
				}
			}
		}
		hisTaskVosByParams = historics;

		// 2.根据当前页和页数获取list
		if (null != hisTaskVosByParams && hisTaskVosByParams.size() > 0) {
			bean.getRecordsHistoricListboxPaging().setTotalSize(
					NumericUtil.nullToZero(hisTaskVosByParams.size()));

			int activePage = bean.getRecordsHistoricListboxPaging()
					.getActivePage();
			int pageSize = bean.getRecordsHistoricListboxPaging().getPageSize();
			List<HistoricTaskVo> taskPageList = pageHistoricTaskVos(
					hisTaskVosByParams, activePage, pageSize);

			ListModel dataList = new BindingListModelList(taskPageList, true);
			bean.getRecordsHistoricListbox().setModel(dataList);
		}

		else {
			PubUtil.clearListbox(bean.getRecordsHistoricListbox());
		}
	}

	public void onListboxPaging() {
		if (null != hisTaskVosByParams && hisTaskVosByParams.size() > 0) {
			bean.getRecordsHistoricListboxPaging().setTotalSize(
					NumericUtil.nullToZero(hisTaskVosByParams.size()));

			int activePage = bean.getRecordsHistoricListboxPaging()
					.getActivePage();
			int pageSize = bean.getRecordsHistoricListboxPaging().getPageSize();
			List<HistoricTaskVo> taskPageList = pageHistoricTaskVos(
					hisTaskVosByParams, activePage, pageSize);

			ListModel dataList = new BindingListModelList(taskPageList, true);
			bean.getRecordsHistoricListbox().setModel(dataList);
			
			historicTaskVo = null;
		}
	}

	private List<HistoricTaskVo> pageHistoricTaskVos(List<HistoricTaskVo> list,
			int activePage, int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);
	}

	/**
	 * 绑定下拉框
	 */
	private void bindCombobox() {
		// 流程分类
		List<NodeVo> categoryNodeVoList = new ArrayList<NodeVo>();
		String[][] categoryOption = { { "66", "信息修改" }, { "67", "入职" },
				{ "68", "转正" }, { "69", "调配" }, { "70", "调薪" }, { "71", "离职" } };
		for (int i = 0; i < categoryOption.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(categoryOption[i][j]);
				nodeVo.setName(categoryOption[i][j + 1]);
			}
			categoryNodeVoList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getCategoryId(), categoryNodeVoList);

		// 流程状态
		List<NodeVo> statusNodeList = new ArrayList<NodeVo>();
		String[][] option = { { "0", "在途" }, { "1", "结束" } };
		for (int i = 0; i < option.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(option[i][j]);
				nodeVo.setName(option[i][j + 1]);
			}
			statusNodeList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getIsEnd(), statusNodeList);

	}

}
